package com.ndhutu.ee.util.ali.rtc;

import com.ndhutu.ee.util.StringUtil;

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 阿里RTC音视频通话工具类
 * @Author Shane
 * @Date 2019/9/1810:22
 * @param
 * @return
 **/
public class RTCUtil {
    public static void createChannel() throws Exception{
        String channelId = StringUtil.getUUIDStr();

    }

    /**
     * 下发令牌
     * @Author Shane
     * @Date 2019/9/1812:29
     * @param userId    用户标识，可使用userId或由UUID生成
     * @return
     **/
    public static Map<String, Object> grantToken(RTCConfig config, String channelId, Integer userId) throws NoSuchAlgorithmException {
//        String channelId = StringUtil.getUUIDStr();
        String nonce = StringUtil.getUUIDStr();
        Long timestamp = System.currentTimeMillis()/1000;

        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.update(config.getAppId().getBytes());
        digest.update(config.getAppKey().getBytes());
        digest.update(channelId.getBytes());
        digest.update((userId+"").getBytes());
        digest.update(nonce.getBytes());
        digest.update(Long.toString(timestamp).getBytes());

        String token = DatatypeConverter.printHexBinary(digest.digest()).toLowerCase();

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("appId", config.getAppId());
        data.put("userId", userId);
        data.put("channelId", channelId);
        data.put("nonce", nonce);
        data.put("timestamp", timestamp);
        data.put("token", token);
        data.put("gslb", config.getGslb());

        return data;
    }

    public static void main(String[] args) throws Exception{
        String appId = "3dp5zu7a";
        String appKey = "6cac85aed14748d0dcbd9576c10b84b9";
        String gslb = "https://rgslb.rtc.aliyuncs.com";
        String accessKeyId = "LTAI4FhCTJbd2621A6wkWRrp";
        String accessKeySecret = "smBSYP1whk8fjKibiWgvRikLSJB64k";

        RTCConfig config = new RTCConfig() {
            @Override
            public String getAppId() {
                return appId;
            }

            @Override
            public String getAppKey() {
                return appKey;
            }

            @Override
            public String getGslb() {
                return gslb;
            }

            @Override
            public String getAccessKeyId() {
                return accessKeyId;
            }

            @Override
            public String getAccessKeySecret() {
                return accessKeySecret;
            }
        };
        String channelId = StringUtil.getUUIDStr();
        Map<String, Object> tokenData = grantToken(config, channelId, 1);
        System.out.println(tokenData);
    }
}
